//
//  TTDetailHeaderView.m
//  TaoTuo
//
//  Created by admin on 2019/8/24.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDetailHeaderView.h"
#import "TTDetailModel.h"
#import "TYCyclePagerView.h"
#import "TYPageControl.h"
#import "TYCyclePagerViewCell.h"
#import "YBImageBrowser.h"
#import "TTUpDownButton.h"
#import "TTGoodsDetailInfoView.h"
#import <UIView+TYAlertView.h>
#import "TTDetailSimilarityGoodsView.h"

static NSString *detailBannerCellIdentifier = @"detailBannerCellIdentifier";


@interface TTDetailHeaderView ()<TYCyclePagerViewDataSource, TYCyclePagerViewDelegate>

@property (nonatomic, strong, nullable) TTDetailModel *model;
@property (nonatomic, copy) NSString *styleLibraryId;

@property (nonatomic, strong) TYCyclePagerView *pagerView;
@property (nonatomic, strong) TYPageControl *pageControl;

/// 价格这一块bgView
@property (nonatomic, strong) UIView *priceBGView;
@property (nonatomic, strong) UILabel *priceLabel;  // 价格
/// 标签价格
@property (nonatomic, strong) UILabel *tagPriceLabel;
@property (nonatomic, strong) UILabel *titleLabel;  // 标题
@property (nonatomic, strong) UIButton *saleBtn;   // 已售
@property (nonatomic, strong) TTUpDownButton *collectionBtn;    // 收藏
///立即分享按钮
@property (nonatomic, strong) UIButton *shareBtn;

// 选择货品这一块
@property (nonatomic, strong) TTGoodsDetailInfoView *infoView;
/// 相似商品
@property (nonatomic, strong) TTDetailSimilarityGoodsView *similartyView;

@end

@implementation TTDetailHeaderView

+ (instancetype)headerViewWithDetailModel:(TTDetailModel *)model
{
    TTDetailHeaderView *headerView = [[self alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH + 120)];
    headerView.model = model;
    return headerView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.subject = [RACSubject subject];
        self.backgroundColor = UIColorHex(#F5F5F5);
        [self setupSubviews];
        
    }
    return self;
}

/// 分享
- (void)shareAction
{
    if ([self.viewController respondsToSelector:@selector(shareAction)]) {
        [self.viewController performSelector:@selector(shareAction)];
    }
}

- (void)setIsCollection:(BOOL)isCollection
{
    self.collectionBtn.selected = isCollection;
}

- (void)setModel:(TTDetailModel *)model similarArr:(nonnull NSArray *)similarArr styleLibraryId:(nullable NSString *)styleLibraryId isCollection:(BOOL)isCollection
{
    if (model == nil) {
        return;
    }
    self.model = model;
    self.styleLibraryId = styleLibraryId;
    
    self.collectionBtn.selected = isCollection;
    
    self.pageControl.numberOfPages = model.GoodsImageList.count;
    [self.pagerView reloadData];
    // 价格
    NSString *price = [NSString stringWithFormat:@"￥%@", model.Price];
    NSMutableAttributedString *priceAttr = [[NSMutableAttributedString alloc] initWithString:price];
    [priceAttr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:[price rangeOfString:@"￥"]];
    self.priceLabel.attributedText = priceAttr;
    
    // 标签价
    if (model.LabelPrice.length > 0) {
        NSString *labelPrice = [NSString stringWithFormat:@"¥%@", model.LabelPrice];
        NSString *tagPrice = [NSString stringWithFormat:@"标签价 %@", labelPrice];
        NSMutableAttributedString *tagPriceAttr = [[NSMutableAttributedString alloc] initWithString:tagPrice];
        [tagPriceAttr addAttribute:NSStrikethroughStyleAttributeName value:@2 range:[tagPrice rangeOfString:labelPrice]];
        self.tagPriceLabel.attributedText = tagPriceAttr;
    }
    
    // 标题
    self.titleLabel.text = [NSString stringWithFormat:@"%@", model.GoodsTitle];
    NSString *saleStr = [NSString stringWithFormat:@"已售 %@件", model.SalesVolume];
    [self.saleBtn setTitle:saleStr forState:UIControlStateNormal];
    
    self.infoView.model = model;
    
    self.similartyView.dataArray = similarArr;
    
    
    [self setNeedsLayout];
}

// 收藏 取消收藏
- (void)collectionBtnClick:(TTUpDownButton *)sender
{
    NSDictionary *dic = @{
                          @"param.styleLibraryId" : self.styleLibraryId
                          };
    NSString *urlStr = sender.selected ? setCancelCollection_api : setCollection_api;
    [[LLNetworkManagerTool sharedManager] postUrlString:urlStr parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        sender.selected = !sender.selected;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelORAddCollectionNotify_key" object:@(!sender.selected)];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.viewController.view];
    
}

#pragma mark - TYCyclePagerViewDataSource
- (NSInteger)numberOfItemsInPagerView:(TYCyclePagerView *)pageView {
    return self.model.GoodsImageList.count;
}

- (UICollectionViewCell *)pagerView:(TYCyclePagerView *)pagerView cellForItemAtIndex:(NSInteger)index {
    TTDetailBannerModel *bannerModel = self.model.GoodsImageList[index];
    TYCyclePagerViewCell *cell = [pagerView dequeueReusableCellWithReuseIdentifier:detailBannerCellIdentifier forIndex:index];
    NSString *imgUrlStr = bannerModel.FileType == 0 ? bannerModel.ImageUrl : bannerModel.VideoCoverImage;
    [cell setImageUrlString:imgUrlStr isVideo:bannerModel.FileType == 1];
    return cell;
}

- (TYCyclePagerViewLayout *)layoutForPagerView:(TYCyclePagerView *)pageView {
    TYCyclePagerViewLayout *layout = [[TYCyclePagerViewLayout alloc]init];
    layout.itemSize = CGSizeMake(pageView.width, pageView.height);
    layout.itemHorizontalCenter = YES;  // 居中显示
    layout.layoutType = TYCyclePagerTransformLayoutNormal;

    return layout;
}

- (void)pagerView:(TYCyclePagerView *)pageView didScrollFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    _pageControl.currentPage = toIndex;
    
    TTDetailBannerModel *bannerModel = self.model.GoodsImageList[toIndex];
    self.pageControl.hidden = bannerModel.FileType == 1;
    self.playerView.hidden = bannerModel.FileType != 1;
    
    if (bannerModel.FileType == 1) {
        self.playerView.frame = CGRectMake(toIndex * self.width, 0, self.width, self.width);
        self.playerView.videoUrlString = bannerModel.ImageUrl;
        self.canRotation = YES;
        [self.playerView play];
        
    } else {
        self.canRotation = NO;
        [self.playerView pause];
    }
    
    [self.subject sendNext:@(self.canRotation)];
    
}

- (void)pagerView:(TYCyclePagerView *)pageView didSelectedItemCell:(__kindof UICollectionViewCell *)cell atIndex:(NSInteger)index
{
//    NSLog(@"选中了 -->%ld", index);
//    TYCyclePagerViewCell *tyCell = (TYCyclePagerViewCell *)cell;
    
    TTDetailBannerModel *bannerModel = self.model.GoodsImageList[index];
    if (bannerModel.FileType == 1) {
        return;
    }
    // 查看图片
    NSMutableArray *imgs = [NSMutableArray array];
    @autoreleasepool {
        for (TTDetailBannerModel *bannerModel in self.model.GoodsImageList) {
            NSString *imgUrlStr = bannerModel.FileType == 0 ? bannerModel.ImageUrl : bannerModel.VideoCoverImage;
            YBIBImageData *data = [YBIBImageData new];
            data.imageURL = [NSURL URLWithString:imgUrlStr];
            [imgs addObject:data];
        }
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = imgs;
        browser.currentPage = index;
        [browser show];
    }
    
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(17);
        make.left.mas_equalTo(10);
    }];
    
    [self.tagPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.priceLabel.mas_right).offset(10);
        make.centerY.equalTo(self.priceLabel);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.priceLabel.mas_bottom).offset(19);
        make.left.equalTo(self.priceLabel);
        make.right.equalTo(self.priceBGView.mas_right).offset(-21);
    }];
    
    [self.saleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).mas_offset(10);
        make.left.equalTo(self.priceLabel);
    }];
    
    [self.collectionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.priceLabel);
        make.right.equalTo(self.priceBGView.mas_right).mas_offset(-21);
        make.width.height.mas_equalTo(40);
    }];
    
    [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.saleBtn);
        make.right.equalTo(self.priceBGView.mas_right).mas_offset(-15);
    }];
    
//    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.equalTo(self);
//        make.height.mas_equalTo(10 * kScale);
//    }];
    
    [self layoutIfNeeded];
    
    self.priceBGView.height = self.saleBtn.bottom + 13;
    
    self.infoView.frame = CGRectMake(10, self.priceBGView.bottom + 10, self.width - 20, 150);
    
    self.similartyView.top = self.infoView.bottom + 10;
    
    self.height = self.similartyView.bottom + 10;
    
    
}

- (void)setupSubviews
{
    [self addPagerView];
    [self addPageControl];
    
    [self.pagerView reloadData];
    
}

- (void)addPagerView
{
    TYCyclePagerView *pagerView = [[TYCyclePagerView alloc]init];
    pagerView.frame = CGRectMake(0, 0, self.width, self.width);
    pagerView.isInfiniteLoop = NO;
//    pagerView.autoScrollInterval = 3.0;
    pagerView.dataSource = self;
    pagerView.delegate = self;
    [pagerView registerClass:[TYCyclePagerViewCell class] forCellWithReuseIdentifier:detailBannerCellIdentifier];
    [self addSubview:pagerView];
    self.pagerView = pagerView;
}

- (void)addPageControl
{
    TYPageControl *pageControl = [[TYPageControl alloc]init];
    pageControl.frame = CGRectMake(0, self.pagerView.bottom - 40 * kScale, self.width, 40 * kScale);
    pageControl.currentPageIndicatorSize = CGSizeMake(20, 8);
    pageControl.pageIndicatorSize = CGSizeMake(8, 8);
    pageControl.currentPageIndicatorTintColor = kMainColor;
    pageControl.pageIndicatorTintColor = UIColorHex(DDDDDD);
    pageControl.hidesForSinglePage = YES;
    pageControl.numberOfPages = self.model.GoodsImageList.count;
    [self.pagerView addSubview:pageControl];
    self.pageControl = pageControl;
}


- (LLPlayerContainerView *)playerView
{
    if (!_playerView) {
        _playerView = [[LLPlayerContainerView alloc] initWithFrame:self.pagerView.frame superView:self.pagerView.collectionView inViewController:self.viewController];
    }
    return _playerView;
}

- (UIView *)priceBGView
{
    if (!_priceBGView) {
        _priceBGView = [[UIView alloc] initWithFrame:CGRectMake(10, self.playerView.bottom + 10, self.width - 20, 100)];
        _priceBGView.backgroundColor = UIColor.whiteColor;
        _priceBGView.layer.cornerRadius = 10;
        [self addSubview:_priceBGView];
    }
    return _priceBGView;
}

- (UILabel *)priceLabel
{
    if (!_priceLabel) {
        _priceLabel = [UILabel labelWithTitle:@"" color:UIColorHex(FF1F1F) fontSize:24];
        [self.priceBGView addSubview:_priceLabel];
    }
    return _priceLabel;
}

- (UILabel *)tagPriceLabel
{
    if (!_tagPriceLabel) {
        _tagPriceLabel = [UILabel labelWithTitle:@"" color:UIColorHex(999999) fontSize:12];
        [self.priceBGView addSubview:_tagPriceLabel];
    }
    return _tagPriceLabel;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel labelWithTitle:@"" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:15]];
        _titleLabel.numberOfLines = 0;
        [self.priceBGView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UIButton *)saleBtn
{
    if (!_saleBtn) {
        _saleBtn = [UIButton createButtonWithTitle:@"" titleColor:UIColorHex(999999) titleFont:[UIFont systemFontOfSize:13] backgroundColor:nil target:nil action:nil];
        [_saleBtn setImage:[UIImage imageNamed:@"已售出"] forState:UIControlStateNormal];
        _saleBtn.enabled = NO;
        [self.priceBGView addSubview:_saleBtn];
    }
    return _saleBtn;
}

- (TTUpDownButton *)collectionBtn
{
    if (!_collectionBtn) {
        _collectionBtn = [TTUpDownButton buttonWithType:UIButtonTypeCustom];
        [_collectionBtn setTitle:@"收藏" forState:UIControlStateNormal];
        [_collectionBtn setImage:[UIImage imageNamed:@"weishoucang"] forState:UIControlStateNormal];
        [_collectionBtn setTitle:@"取消" forState:UIControlStateSelected];
        [_collectionBtn setImage:[UIImage imageNamed:@"yishoucang"] forState:UIControlStateSelected];
        [_collectionBtn setTitleColor:UIColorHex(999999) forState:UIControlStateNormal];
        _collectionBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        [_collectionBtn addTarget:self action:@selector(collectionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _collectionBtn.isNeedLogin = YES;
        [self.priceBGView addSubview:_collectionBtn];
    }
    return _collectionBtn;
}


- (UIButton *)shareBtn
{
    if (!_shareBtn) {
        _shareBtn = [UIButton createButtonWithTitle:@"分享" titleColor:UIColorHex(#4D4D4D) titleFont:[UIFont systemFontOfSize:13] backgroundColor:nil target:self action:@selector(shareAction)];
        [self.priceBGView addSubview:_shareBtn];
        [_shareBtn setImage:[UIImage imageNamed:@"share_black"] forState:UIControlStateNormal];
        _shareBtn.contentEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
    }
    return _shareBtn;
}

- (TTGoodsDetailInfoView *)infoView
{
    if (!_infoView) {
        _infoView = [TTGoodsDetailInfoView createViewFromNib];
        [self addSubview:_infoView];
    }
    return _infoView;
}

- (TTDetailSimilarityGoodsView *)similartyView
{
    if (!_similartyView) {
        _similartyView = [[TTDetailSimilarityGoodsView alloc] initWithFrame:CGRectMake(10, 0, self.width - 20, 216)];
        [self addSubview:_similartyView];
    }
    return _similartyView;
}



@end
